import { observable, action } from 'mobx';
import * as Apis from "../../api/customerApis";
import { Toast, Bubble, Tools } from 'weaver-mobile';
import { BrowserHrm, ListViewPage, RouteLayout, MapPage,Share  } from 'weaver-mobile-page';
import * as adapter from '../../constants/adapter';
const getLabel = Tools.getLabel;
const getCurrentPosition = MapPage.getCurrentPosition;
export default class CustomerCardStore {
  comObj = {};
  params = {};
  @observable tabs = [
    { title: getLabel('2121', '详细信息'), key: "info" },
    { title: getLabel('17532', '联系记录'), key: "contact" },
    { title: getLabel('32922', '商机'), key: "chance" },
  ];
  @observable fieldItems = [];
  @observable contacterItems = [];
  @observable planItems = [];
  @observable contacterCount = 0;
  @observable planCount = 0;
  @observable customerId = "";
  @observable customerName = "";
  @observable customerManager = "";
  @observable customerManagerId = "";
  @observable customerAddress = "";
  @observable customerDistrict = "";
  @observable customerCity = "";
  @observable customerPosition = "";
  @observable fixedPosition = false;
  @observable lat1 = "";
  @observable lng1 = "";
  @observable hasPosition = true;
  @observable getUserPosition = false;
  @observable location = "";
  @observable customerConcerned = false;
  @observable canEdit = false;
  @observable canView = false;
  @observable initResponsed = false;// 是否已经得到初始化数据的响应
  @observable initSuccessed = false;// 初始化数据是否获取成功
  @observable initFailedMsg = "";   // 初始化处理失败的原因
  @observable managerBrowser = {};
  @observable raidus = 1;
  @observable tabPage = "info";
  @observable refreshing = false;
  // list
  @observable chanceListStore = {};
  // layout
  @observable createChanceLayout = {};
  @observable createContacterLayout = {};
  @observable customerMapLayout = {};
  @observable contacterListLayout = {};
  @observable workplanListLayout = {};
  @observable contacterCardLayout = {};
  @observable commerceCardLayout = {};
  @observable signInOutLayout = {};
  @observable shareListLayout = {};
  @observable chanceCardLayout = {};
  @observable changeLocalLayout = {};
  @observable crmDetailAndEditLayout = {};
  @observable workplanCreateLayout = {};
  @observable workplanViewLayout = {};
  @observable addressItem = [];
  @observable isManager = false;
  @observable userCurrentlat = "";
  @observable userCurrentlng = "";
  @observable canShare = false;
  @observable shareCustomerLayout = {};
  @observable shareStore = {};
  @observable userId = "";
  @observable onlyView = false;

  @action
  doNew = (comObj, params) => {
    this.comObj = comObj;
    this.params = params;
    if (params.tabPage) {
      this.tabPage = params.tabPage;
    }
    window.crmCard = this;
  }

  @action
  doInit = () => {
    let params = this.params;
    this.refreshing = true;
    Apis.getCustomerCard(params).then(data => {
      this.doInitCallBack(params, data);
    });
  }

  @action
  doInitCallBack = (params, data) => {
    this.refreshing = false;
    this.initResponsed = true;
    if (data.status == "0") {
      this.initSuccessed = false;
      this.initFailedMsg = data.errorMsg;
    } else {
      const currentPath = this.comObj.props.location.pathname;
      this.managerBrowser = new BrowserHrm.Store({ route: currentPath, id: "customerManager" });
      this.chanceListStore = new ListViewPage.Store({ route: currentPath, id: "chanceListStore" });
      this.createChanceLayout = new RouteLayout.Store({ route: currentPath, id: 'createChanceLayout' });
      this.createContacterLayout = new RouteLayout.Store({ route: currentPath, id: 'createContacterLayout' });
      this.customerMapLayout = new RouteLayout.Store({ route: currentPath, id: 'customerMapLayout' });
      this.contacterListLayout = new RouteLayout.Store({ route: currentPath, id: 'contacterListLayout' });
      this.workplanListLayout = new RouteLayout.Store({ route: currentPath, id: 'workplanListLayout' });
      this.chanceCardLayout = new RouteLayout.Store({ route: currentPath, id: 'chanceCardLayout' });
      this.contacterCardLayout = new RouteLayout.Store({ route: currentPath, id: 'contacterCardLayout' });
      this.commerceCardLayout = new RouteLayout.Store({ route: currentPath, id: 'commerceCardLayout' });
      this.signInOutLayout = new RouteLayout.Store({ route: currentPath, id: 'signInOutLayout' });
      this.shareListLayout = new RouteLayout.Store({ route: currentPath, id: 'shareListLayout' });
      this.changeLocalLayout = new RouteLayout.Store({ route: currentPath, id: 'changeLocalLayout' });
      this.crmDetailAndEditLayout = new RouteLayout.Store({ route: currentPath, id: 'crmDetailAndEditLayout' });
      this.workplanCreateLayout = new RouteLayout.Store({ route: currentPath, id: 'workplanCreateLayout' });
      this.workplanViewLayout = new RouteLayout.Store({ route: currentPath, id: 'workplanViewLayout' });

      this.shareCustomerLayout = new RouteLayout.Store({ route: currentPath, id: 'shareCustomerLayout' });
      this.shareStore = new Share.Store({ route: currentPath+'/shareCustomerLayout', id: 'share' });
   

      this.initSuccessed = true;
      this.canEdit = data.canEdit;
      this.canView = data.canView;
      this.canShare = data.canShare;
      this.userId = data.loginid;
      this.onlyView = data.onlyView;
      this.isManager = data.isManager;
      this.fieldItems = data.customerInfo;
      this.addressItem = data.addressInfo;
      this.contacterItems = data.contacterInfo;
      this.planItems = data.planInfo;
      this.contacterCount = data.contacterCount;
      this.planCount = data.planCount;
      this.customerId = data.customerId;
      this.customerName = data.customerName;
      this.customerManager = data.customerManager;
      this.customerManagerId = data.customerManagerId;
      this.customerAddress = data.customerAddress;
      this.customerPosition = data.customerPosition;
      this.customerCity = data.customerCity;
      this.customerDistrict = data.customerDistrict;
      this.lat1 = data.lat1;
      this.lng1 = data.lng1;
      this.fixedPosition = data.fixedPosition;
      
      if (this.lat1 === "" || this.lng1 === ""||parseInt(this.lat1)===0||parseInt(this.lng1)===0) {
        this.hasPosition = false;
      } else {
        this.hasPosition = true;
      }
      this.comObj.customerConcerned = data.customerConcerned;
      setTimeout(() => {
        this.comObj.state.headLeadClick && this.comObj.cardheadRef.showOpenSystemApp();
        this.comObj.setState({ headLeadClick: false })
      }, 1000);
    }
  }

  @action
  doClear = () => {
    this.initResponsed = false;
    this.initSuccessed = false;
    this.initFailedMsg = "";
    this.tabPage = "info";
  }

  @action
  setCustomerConcerned(concerned) {
    this.customerConcerned = !concerned;
    let params = { relatedIds: this.customerId, type: "crm", important: concerned ? 0 : 1 };
    Apis.setCustomerConcerned(params).then(data => {
      Bubble.success(getLabel('83551', "保存成功"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2);
      if (window.crmGlobal && window.crmGlobal.listTabIndex == "attention") {
        window.crmGlobal.doSearch();
      }
    });
  }

  @action
  changeManager = (id) => {
    if (id == "" || id == this.customerManagerId) {
      return;
    }
    const params = { customerId: this.customerId, fieldType: "BROWSER", fieldName: "manager", oldValue: this.customerManagerId, oldValueSpan: this.customerManager, newValue: id };
    Toast.loading(getLabel('388626', '正在保存，请稍后...'), 0);
    Apis.updateCustomer(params).then(data => {
      Toast.hide();
      Bubble.success(getLabel('83551', "保存成功"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
        if (window.crmGlobal) {
          window.crmGlobal.doSearch();
        }
        this.doInit();
      });
    });
  }

  //修改定位+地址
  @action
  changeAddress = (data) => {

    //地址
    let address1 = data.address + data.name;
    //省
    let province = "";
    //市
    let city = "";
    //县
    let district = "";

    Tools.callApi(
      {
        url: 'https://restapi.amap.com/v3/geocode/regeo',
        method: 'GET',
        params: {
          key: "deee9801361e46e9340bd492ae45b90d",
          location: data.location,
        },
        includeCredentials: false,
      }
    ).then(result => {
      // console.log(data);
      if (result.status == '1') {
        province = result.regeocode.addressComponent.province;
        city = result.regeocode.addressComponent.city;
        district = result.regeocode.addressComponent.district;
       // address1 = (province ? province : "") + (city ? city : "") + (district ? district : "") + address1;
        const params = {
          customerId: this.customerId,
          city: city != "" ? city : province,
          city_old: this.customerCity,
          district: district,
          district_old: this.customerDistrict,
          address: address1,
          address_old: this.customerAddress,
          location: data.location,
        }

        Toast.loading(getLabel('388626', '正在保存，请稍后...'), 0);
        Apis.changePosition(params).then(date => {
          Toast.hide();
          Bubble.success(getLabel('83551', "保存成功"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
            if (window.crmGlobal) {
              window.crmGlobal.doSearch();
            }
            this.getUserPosition = false;
            this.doInit();
          });
        });
      }
    })

    // let address = data.pname + data.cityname + data.adname + data.address + data.name;
    // if (data.pname === data.cityname) {
    //   address = data.cityname + data.adname + data.address + data.name;
    // }

  }

  @action
  tabChange(page) {
    this.tabPage = page;
    if (page == "chance") {
      this.getChanceList();
    }
  }

  @action
  toContactTab = () => {
    if (this.tabPage == "contact") {
      this.comObj.contactListRef.doSearch();
    } else {
      this.tabChange("contact");
    }
  }

  @action
  getChanceList() {
    const params = { customerid: this.customerId };
    Apis.getChanceListResult(params).then(data => {
      const dataKey = data.datas;
      this.chanceListStore.clearData();
      this.chanceListStore.getData({ dataKey });
    });
  }
  getCurrentPosition = () => {
    getCurrentPosition().then((result) => {
      if (typeof (result) !== "undefined") {
        if (result.status === -1) {
          Bubble.error(result.errMsg, 4, { top: '50%', color: 'red' }, 1, () => this.comObj.props.history.go(-1));
          return;
        } else {
          this.getUserPosition = true;
          this.lat1 = result.position[1];
          this.lng1 = result.position[0];
        }

      }
    });
  }
  @action
  getUserCurrentPosition = () => {
    getCurrentPosition().then((result) => {
      // console.log(result)
      if (typeof (result) !== "undefined") {
        if (result.status === -1) {
          Bubble.error(result.errMsg, 4, { top: '50%', color: 'red' }, 1, () => { });
          return;
        } else {
          this.getUserPosition = true;
          this.userCurrentAddress = result.address;
          this.userCurrentlat = result.position[1];
          this.userCurrentlng = result.position[0];
        }
      }
    });
  }
  @action
  deleteWorkPlan = (id) => {
    Toast.loading(getLabel('388626', '正在保存，请稍后...'), 0);
    Apis.deleteWorkPlan({ workid: id }).then(data => {
      this.doInit();
      Bubble.success(getLabel('83551', "保存成功"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
        Toast.hide();
      });
    });
  }

  @action
  completeWorkPlan = (id) => {
    Toast.loading(getLabel('388626', '正在保存，请稍后...'), 0);
    Apis.completeWorkPlan({ planIds: id }).then(data => {
      this.doInit();
      Bubble.success(getLabel('83551', "保存成功"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
        Toast.hide();
      });
    });
  }
  //删除客户
  @action
  doDelete = () => {
    const params = { customerIds: this.customerId };
    Apis.crmDelete(params).then(data => {
      if (data.status === "success") {
        Bubble.success(getLabel('83472', '删除成功!'), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
          this.comObj.props.history.go(-1);
          if (typeof (this.comObj.props.store !== "undefined") && this.comObj.props.store) {
            this.comObj.props.store.doInit();
          }
        }
        );
        window.crmGlobal && window.crmGlobal.doSearch();
      } else {
        Bubble.error(data.msgcode, 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => { });
      }
    });
  }
  
}
